<?php

namespace Home\Controller;

class CollectController extends BaseController {

    public function getList() {
        $where['c.user_id'] = $this->user_id;
        $p = I('p', 0, 'intval');

        if ($p) {
            $page = $p * 10;
        }

        $list = M()
                ->table('ot_collect c')
                ->join('ot_goods g on c.goods_id = g.goods_id')
                ->field('c.collect_id,c.goods_id,g.goods_name,g.head_img,g.price')
                ->where($where)
                ->order('c.create_time desc')
                ->limit($page, 10)
                ->select();

        if ($list) {
            foreach ($list as &$val) {
                $val['head_img'] = 'http://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $val['head_img'];
            }
            unset($val);
        } else {
            $list = [];
        }

        $this->success('获取成功', $list);
    }

    public function add() {
        $goods_id = I('goods_id', 0, 'intval');
        if ($goods_id == 0) {
            $this->error('请选择商品');
        }

        $data['goods_id'] = $goods_id;
        $data['user_id'] = $this->user_id;

        $res = M('Collect')->add($data);

        if ($res) {
            $this->success('收藏成功');
        } else {
            $this->error('收藏失败');
        }
    }

    public function del() {
        $collect_id = I('goods_id', 0, 'intval');
        if ($collect_id == 0) {
            $this->error('请选择要删除的商品');
        }

        $where['goods_id'] = $collect_id;
        $where['user_id'] = $this->user_id;

        $res = M('Collect')->where($where)->delete();

        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

}
